package cool.taomu.box.git

import com.jcraft.jsch.Session
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Provider
import org.eclipse.jgit.api.TransportConfigCallback
import org.eclipse.jgit.transport.JschConfigSessionFactory
import org.eclipse.jgit.transport.OpenSshConfig
import org.eclipse.jgit.transport.SshSessionFactory
import org.eclipse.jgit.transport.SshTransport
import org.eclipse.jgit.transport.Transport
import org.eclipse.jgit.util.FS

class SshProvider implements Provider<TransportConfigCallback> {

	@Inject
	@Named("git.ssh.keypath")
	String sshkeyPath;

	override get() {
		return new TransportConfigCallback() {
			override configure(Transport transport) {
				var sshTransport = transport as SshTransport;
				var jcsf = new JschConfigSessionFactory() {
					override configure(OpenSshConfig.Host host, Session session) {
						session.setConfig("StrictHostKeyChecking", "no");
					}

					override createDefaultJSch(FS fs) {
						var jSch = super.createDefaultJSch(fs);
						jSch.addIdentity(sshkeyPath);
						return jSch;
					}
				};
				SshSessionFactory.instance = new JschConfigSessionFactory() {
					override configure(OpenSshConfig.Host host, Session session) {
						session.setConfig("StrictHostKeyChecking", "no");
					}

					override createDefaultJSch(FS fs) {
						var jSch = super.createDefaultJSch(fs);
						jSch.addIdentity(sshkeyPath);
						return jSch;
					}
				};
				sshTransport.setSshSessionFactory(jcsf);
			}
		}
	}

}
